<?php

/**
 * the forgot password controller
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
class ForgotController extends Controller {

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            )
        );
    }

    public function actionIndex() {
        $email = '';
        if (r()->isPostRequest) {
            $email = $_POST['email'];
            $captcha = Yii::app()->getController()->createAction("captcha");
            $code = $captcha->verifyCode;

            if ($code != $_POST['captcha']) {
                user()->setFlash('error', 'Verify code is not correct');
            } else {

                //check email
                if ($_POST['email'] != '') {
                    //check in db
                    if (strpos($_POST['email'], '@')) {
                        $attribute = 'email';
                    } else {
                        $attribute = 'username';
                    }

                    $db = db();
                    //get user in db
                    $user = $db->createCommand()
                            ->select('user_id, username, email')
                            ->from('{{users}}')
                            ->where("$attribute = :value", array(':value' => $_POST['email']))
                            ->queryRow();
                    if ($user == NULL) {
                        //no user exists
                        user()->setFlash('error', 'Invalid user!');
                    } else {
                        //write new row to db and send mail to user
                        $uniqueCode = uniqid();

                        $result = $db->createCommand()
                                ->insert('{{recoveryemails}}', array(
                            'user_id' => $user['user_id'],
                            'uniqid' => $uniqueCode,
                            'created' => time(),
                            'expired' => time() + 7 * 24 * 60 * 60
                        ));
                        if ($result) {
                            //send new email
                            EmailHelper::sendForgotPassword($user['email'], $user['username'], app()->createAbsoluteUrl('/user/forgot/recovery', array('key' => $uniqueCode)));

                            user()->setFlash('success', 'An email has sent to your email');

                            $this->refresh();
                        } else {
                            user()->setFlash('error', 'Sorry, please try again');
                        }
                    }
                } else {
                    user()->setFlash('error', 'Username or Email is required');
                }
            }
        }
        $this->render('index', array(
            'email' => $email
        ));
    }

    /**
     * recovery password form
     * @param string $key
     */
    public function actionRecovery($key){
        //check from db
        $userId = db()->createCommand()
                ->select('user_id')
                ->from('{{recoveryemails}}')
                ->where('uniqid = :key AND expired > :exp', array(':key' => $key, ':exp' => time()))
                ->queryScalar();

        if(!$userId){
            user()->setFlash('error', 'Your valid key is not match');

            $this->redirect(array('/user/register'));
        }

        if(r()->isPostRequest){
            //check valid password
            if($_POST['password'] !== $_POST['repassword'] || strlen($_POST['password']) < 6){
                //error
                user()->setFlash('error', 'Confirm new password does not match or too short');
            }else{
                //save new password
                $model = User::model()->findByPk($userId);

                $model->password = $_POST['password'];

                if($model->save()){
                    user()->setFlash('success', 'Your password has been change');

                    //delete recovery email records
                    db()->createCommand()
                            ->delete('{{recoveryemails}}', 'user_id='.$model->user_id);

                    //redirect to loin page
                    $this->redirect(array('/site/login'));
                }else{
                    user()->setFlash('error', 'Sorry, please try again');
                }
            }
        }

        //render view
        $this->render('recovery');
    }

}